#include "StdAfx.h"
#include "BasicSafeHandle.h"

using namespace Adaptive::Win32;

/*--------------------------------------------------------------------------------
 * Constructor / Dispose / Destructor Methods
 *------------------------------------------------------------------------------*/
#pragma region Constructor / Dispose / Destructor Methods
// <summary>
// Initializes a new instance of the class.
// </summary>
// <remarks>
// This is the default constructor.
// </remarks>
BasicSafeHandle::BasicSafeHandle(): SafeHandle(IntPtr::Zero, false)
{
}
// <summary>
// Initializes a new instance of the class to the specified handle value.
// </summary>
// <param name="originalHandle">The original handle value.</param>
BasicSafeHandle::BasicSafeHandle(IntPtr originalHandle) : SafeHandle(originalHandle, true)
{
}
// <summary>
// Initializes a new instance of the class to the specified handle value.
// </summary>
// <param name="originalHandle">The original handle value.</param>
BasicSafeHandle::BasicSafeHandle(IntPtr^ originalHandle) : SafeHandle(*originalHandle, true)
{
}
// <summary>
// Initializes a new instance of the class to the specified unmanaged handle value.
// </summary>
// <param name="originalHandle">The original handle value.</param>
BasicSafeHandle::BasicSafeHandle(HANDLE originalHandle) : SafeHandle(IntPtr::Zero, true)
{
	IntPtr^ handle;

	handle = gcnew IntPtr((int)originalHandle);
	SetHandle(*handle);
}
#pragma endregion

/*--------------------------------------------------------------------------------
 * Public Properties
 *------------------------------------------------------------------------------*/
#pragma region Public Properties
// <summary>
// Gets the underlying handle value.
// </summary>
// <value>
// An <see cref="IntPtr"/> value indicating the underlying handle.
// </value>
bool BasicSafeHandle::IsInvalid::get()
{
	return (IsClosed || handle == IntPtr::Zero);
}
// <summary>
// Gets a value indicating whether the underlying handle is invalid.
// </summary>
// <value>
// <b>true</b> if the underlying handle value is an invalid handle or null value;
// otherwise, <b>false</b>.
// </value>
IntPtr BasicSafeHandle::HandleValue::get()
{
	return handle;
}
#pragma endregion

/*--------------------------------------------------------------------------------
 * Protected Methods / Event Methods
 *------------------------------------------------------------------------------*/
#pragma region Protected Methods / Event Methods
// <summary>
// Releases the underlying handle value.
// </summary>
bool BasicSafeHandle::ReleaseHandle()
{
	HANDLE handleValue = NULL;
	bool returnValue = false;

	if (!IsInvalid)
	{
		handleValue = (HANDLE)(handle.ToInt32());
		::CloseHandle(handleValue);
		SetHandle(IntPtr::Zero);
		returnValue = true;
	}
	return returnValue;
}
#pragma endregion
